#!/usr/bin/python

import psycopg2
import psycopg2.extras

preparedStatementFactories = {
'Get Character Base Info and Abilities from Primary Key' : """

PREPARE getCharacterFromPk (integer) AS 
SELECT * FROM character
WHERE pk_character = $1;
""",
'Get Character Primary Key from Character Name pattern' : """

PREPARE getCharacterPkFromCharacterName (varchar) AS
SELECT pk_character FROM character
WHERE character_name ILIKE $1;
""",
'Get Character Primary Key from Player Name pattern' : """

PREPARE getCharacterPkFromPlayerName (varchar) AS
SELECT pk_character FROM character
WHERE player_name ILIKE $1;
"""
}

def cleanquotes(val):
    if val is None: return ''
    return str(val).replace("'","\\'").replace('"','\\"')

conn = psycopg2.connect("dbname=postgres user=postgres")
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

# set up prepared statements (only valid per session)
for psf in preparedStatementFactories:
    dict_cur.execute(preparedStatementFactories[psf]);


# Fetch character primary key from a player name substring
dict_cur.execute("execute getCharacterPkFromPlayerName(%s)", ('%jer%',))
pk_character = dict_cur.fetchone()['pk_character'];


populateSkillTabString = """
function populateSkillTab()
{
    /*%(abilCombat)s
    %(attacks)s
    recalcAll();*/
}
""" #% {}

f = open('xsheet-skilltab-template.js', 'r')
skillTabTemplate = f.read()
f.close()

skillTabText = skillTabTemplate % {'populateSkillTab' : populateSkillTabString}

print "Content-Type: text/plain\n\n"
print skillTabText